package cn.bon.emp.controller;

import cn.bon.common.bean.JsonResult;
import cn.bon.common.enums.FileUseFor;
import cn.bon.common.pojo.po.Files;
import cn.bon.common.tool.R;
import cn.bon.emp.service.IFilesService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @Author Lc_cL
 * @Date 2023/12/12
 * @Description
 */

@Slf4j
@Tag(name = "文件接口")
@RestController
@RequestMapping("/emp/file")
public class FileUploadController {
    @Value("${bon.files.uploadPath}")
    private String basePath;
    @Resource
    private IFilesService filesService;

    /**
     * 员工文件上传
     *
     * @param file
     * @return
     */
    @Operation(summary = "文件上传")
    @PostMapping("/{empId}")
    public JsonResult<Files> upload(@PathVariable() @Schema(description = "员工ID") Long empId,
                                    @RequestParam @Schema(description = "附件类型") String type,
                                    MultipartFile file) {
        log.info("文件上传...");

        Files files = new Files();
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        files.setOriginName(originalFilename);

        //后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        files.setSuffix(suffix);

        //文件名和URL
        String fileName = UUID.randomUUID().toString() + suffix;
        files.setReName(fileName);
        files.setFileUrl(basePath + fileName);

        //保存文件
        File dir = new File(basePath);
        if (!dir.exists()) {    //创建存储目录
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(files.getFileUrl()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //设置所属员工ID
        files.setComId(empId);

        //fileUseFor
        for (FileUseFor useFor : FileUseFor.values()) {
            if (type.equals(useFor.getValue())) {
                files.setUseFor(useFor);
                break;
            }
        }

        //写入数据库
        filesService.save(files);
        return R.success(files);
    }


    /**
     * 文件下载
     */
    @GetMapping("/{empId}")
    @Operation(summary = "文件下载")
    public void download(@PathVariable() @Schema(description = "员工ID") Long empId,
                         @RequestParam @Schema(description = "附件类型") String type,
                         HttpServletResponse response) throws UnsupportedEncodingException {
        LambdaQueryWrapper<Files> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Files::getComId, empId);
        for (FileUseFor useFor : FileUseFor.values()) {
            if (type.equals(useFor.getValue())) {
                queryWrapper.eq(Files::getUseFor, useFor);
                break;
            }
        }
        Files file = filesService.getOne(queryWrapper);

        String filename = URLEncoder.encode(file.getOriginName(), "UTF-8");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);//浏览器上提示下载时默认的文件名

        try {
            FileInputStream fileInputStream = new FileInputStream(new File(file.getFileUrl()));
            ServletOutputStream outputStream = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];

            //读取文件流
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Operation(summary = "删除文件")
    @DeleteMapping("/{fileId}")
    public JsonResult<String> delete(@PathVariable @Schema(description = "文件ID") Long fileId) {
        filesService.removeById(fileId);
        return R.success("删除成功");
    }
}
